<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>证书管理</el-breadcrumb-item>
      <el-breadcrumb-item>新增证书</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-form ref="addFormRef" :model="addForm" label-width="150px" :rules="addFormRules" class="addForm">
        <el-form-item label="成员姓名" prop="member_id">
          <el-select
            v-model="addForm.member_id"
            filterable
            remote
            placeholder="请输入成员姓名"
            :remote-method="getMembers"
            :loading="loading"
            clearable
            class="memberSelect"
            style="width: 100%;"
          >
            <el-option v-for="member in members" :key="member.name" :label="member.name" :value="member.id">
              <span style="float: left">{{ member.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ member.id_num }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证书信息" prop="LiscenseInfo">
          <el-row :gutter="8">
            <el-col :span="7">
              <el-select v-model="addForm.name" placeholder="请选择方法" clearable>
                <el-option v-for="item in liscenseNames" :key="item.id" :label="item.name" :value="item.name"></el-option>
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-select v-model="addForm.level" placeholder="请选择等级" clearable>
                <el-option v-for="item in liscenseLevels" :key="item.id" :label="item.level" :value="item.level"> </el-option>
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-select v-model="addForm.organ" placeholder="请选择发证机构" clearable>
                <el-option v-for="item in liscenseOrgans" :key="item.id" :label="item.organ" :value="item.organ"> </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="证书有效期" prop="valid_date" clearable>
          <el-date-picker
            v-model="addForm.valid_date"
            type="daterange"
            range-separator="至"
            start-placeholder="发证日期"
            end-placeholder="过期时间"
            value-format="yyyy-MM-dd"
            :unlink-panels="true"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="证书文件" prop="uploadFile">
          <el-upload
            drag
            :action="uploadURL"
            class="fileUpload"
            :headers="uploadHeader"
            :on-exceed="exceedLimit"
            name="liscensefile"
            :multiple="false"
            :limit="1"
            accept=".pdf,.jpg,.png,.bmp"
            :before-upload="beforeFileUpload"
            ref="uploadRef"
            :on-error="uploadError"
            :on-success="uploadSuccess"
            :on-remove="removeFile"
            id="liscensefile"
            :on-preview="previewFile"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传pdf/jpg/jpeg/png文件，且不超过5MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="createLiscense">立即创建</el-button>
          <el-button @click="resetAddForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预览上传文件的对话框 -->
    <el-dialog title="证书文件预览" :visible.sync="previewDialogVisable" width="50%">
      <pdf :src="previewPath" @num-pages="pageCount = $event" @page-loaded="currentPage = $event" v-if="isPDF"></pdf>
      <el-image v-else style="width: 100%" :src="previewPath" fit="contain" lazy>
        <div slot="error" class="image-slot">
          <i class="el-icon-picture-outline"></i>
        </div>
      </el-image>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="previewDialogVisable = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pdf from 'vue-pdf'

export default {
  components: {
    pdf
  },
  data() {
    var checkLiscense = (rule, value, callback) => {
      if (this.addForm.name === '' || this.addForm.level === '' || this.addForm.organ === '') {
        callback(new Error('请输入证书的完整信息'))
      }
      callback()
    }
    return {
      addForm: {
        member_id: '',
        name: '',
        level: '',
        organ: '',
        valid_date: '',
        fullpath: '',
        filepath: ''
      },
      addFormRules: {
        member_id: [{ required: true, message: '请输入成员姓名', trigger: 'blur' }],
        LiscenseInfo: [{ validator: checkLiscense, trigger: 'blur' }],
        valid_date: [{ required: true, message: '请输入证书有效时间段', trigger: 'blur' }]
      },
      liscenseNames: [],
      liscenseLevels: [],
      liscenseOrgans: [],
      loading: false,
      members: [],
      // 上传文件的请求头
      uploadHeader: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 上传文件的请求路径（后端路径,上线前一定要更改！！）
      // uploadURL: 'http://127.0.0.1:8000/api/liscense/uploadliscense/',
      uploadURL: this.serverURL + '/api/liscense/uploadliscense/',
      // 预览文件的对话框显示控制
      previewDialogVisable: false,
      previewPath: '',
      // 预览PDF文件的页码信息
      currentPage: 0,
      pageCount: 0,
      isPDF: true
    }
  },
  created() {
    this.getBaseInfo()
  },
  methods: {
    async getBaseInfo() {
      const { data: res } = await this.$http.get('baseinfo/liscensebaseinfo/')
      if (res.meta.status !== 200) {
        return this.$message.error('获取添加证书的基本信息失败')
      }
      this.liscenseNames = res.data.liscense_name
      this.liscenseLevels = res.data.liscense_level
      this.liscenseOrgans = res.data.liscense_organ
    },
    // 根据用户输入的成员姓名提示成员列表
    async getMembers(query) {
      if (query !== '') {
        this.loading = true
        const params = { query: query, pagenum: 1, pagesize: 20 }
        const { data: res } = await this.$http.get('liscense/getmember', { params: params })
        if (res.meta.status === 200) {
          console.log(res)
          this.loading = false
          this.members = res.data.page_members
        } else {
          this.loading = false
          this.members = []
        }
      } else {
        this.members = []
      }
    },
    // 上传文件个数超过限制时的钩子函数
    exceedLimit() {
      return this.$message.error('只能上传一个文件')
    },
    // 文件上传之前的钩子函数
    beforeFileUpload(file) {
      let fileName = file.name.substring(file.name.lastIndexOf('.') + 1)
      const typeArray = ['pdf', 'png', 'jpg', 'jpeg', 'bmp']
      const indexOfType = typeArray.indexOf(fileName.toLowerCase())
      if (indexOfType === -1) {
        this.$refs.uploadRef.abort()
        this.$refs.uploadRef.clearFiles()
        return this.$message.warning('只能上传pdf/jpg/jpeg/png文件，且不超过5MB')
      }
    },
    // 上传文件出错时的处理函数
    uploadError() {
      this.$refs.uploadRef.abort()
      this.$refs.uploadRef.clearFiles()
      this.addForm.filepath = ''
      return this.$message.error('文件上传失败!请联系管理员')
    },
    // 文件上传成功时的函数
    uploadSuccess(response, file, fileList) {
      console.log(response)
      // console.log(file)
      // console.log(fileList)
      this.addForm.filepath = response.data.shortpath
      console.log(response)
    },
    // 删除文件时的操作
    removeFile(file) {
      this.addForm.filepath = ''
    },
    // 重置添加列表
    resetAddForm() {
      // console.log('重置表格')
      this.$refs.addFormRef.resetFields()
      this.$refs.addFormRef.clearValidate()
      this.$refs.uploadRef.clearFiles()
      this.addForm.filepath = ''
    },
    // 发送请求，创建Liscense
    createLiscense() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('liscense/addliscense/', this.addForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.message)
        }
        this.$message.success('添加证书信息成功！')
        this.$router.push('/liscense')
      })
    },
    // 点击文件预览功能
    previewFile(file) {
      console.log(file)
      const fullpath = file.response.data.fullpath
      this.isPDF = /\.(pdf|PDF)$/.test(fullpath)
      // console.log(this.isPDF)
      this.previewDialogVisable = true
      this.previewPath = fullpath
    }
  }
}
</script>

<style lang="less" scoped>
.addForm {
  width: 60%;
}
</style>
